package com.css.zfzx.fxpg.modules.citycounty.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.citycounty.repository.FxCityCountyNativeRepository;
import com.css.zfzx.fxpg.modules.citycounty.repository.FxCityCountyRepository;
import com.css.zfzx.fxpg.modules.citycounty.repository.entity.FxCityCountyEntity;
import com.css.zfzx.fxpg.modules.citycounty.service.FxCityCountyService;
import com.css.zfzx.fxpg.modules.citycounty.viewobjects.FxCityCountyQueryParams;
import com.css.zfzx.fxpg.modules.citycounty.viewobjects.FxCityCountyVO;
import com.css.zfzx.fxpg.modules.workarea.repository.FxWorkareaNativeRepository;
import com.css.zfzx.fxpg.modules.workarea.repository.FxWorkareaRepository;
import com.css.zfzx.fxpg.modules.workarea.repository.entity.FxWorkareaEntity;
import com.css.zfzx.fxpg.modules.workarea.viewobjects.FxWorkareaQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-26
 */
@Service
@Slf4j
public class FxCityCountyServiceImpl implements FxCityCountyService {

    @Autowired
    private FxCityCountyRepository fxCityCountyRepository;
    @Autowired
    private FxCityCountyNativeRepository fxCityCountyNativeRepository;
    /**
     * 工作区
     */
    @Autowired
    private FxWorkareaNativeRepository fxWorkareaNativeRepository;


    @Override
    public JSONObject queryFxCityCountys(FxCityCountyQueryParams queryParams, int curPage, int pageSize) {
        Page<FxCityCountyEntity> fxCityCountyPage = this.fxCityCountyNativeRepository.queryFxCityCountys(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxCityCountyPage);
        return jsonObject;
    }


    @Override
    public FxCityCountyEntity getFxCityCounty(String id) {
        FxCityCountyEntity fxCityCounty = this.fxCityCountyRepository.findById(id).orElse(null);
        return fxCityCounty;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxCityCountyEntity saveFxCityCounty(FxCityCountyEntity fxCityCounty) {
        String uuid = UUIDGenerator.getUUID();
        fxCityCounty.setId(uuid);
        fxCityCounty.setCreateUser(PlatformSessionUtils.getUserId());
        fxCityCounty.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxCityCountyRepository.save(fxCityCounty);
        return fxCityCounty;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxCityCountyEntity updateFxCityCounty(FxCityCountyEntity fxCityCounty) {
        fxCityCounty.setUpdateUser(PlatformSessionUtils.getUserId());
        fxCityCounty.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxCityCounty.getId();
        FxCityCountyEntity one = fxCityCountyRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxCityCounty, one);
        this.fxCityCountyRepository.save(one);
        return fxCityCounty;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxCityCountys(List<String> ids) {
        List<FxCityCountyEntity> fxCityCountyList = this.fxCityCountyRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxCityCountyList) && fxCityCountyList.size() > 0) {
            for (FxCityCountyEntity fxCityCounty : fxCityCountyList) {
                this.fxCityCountyRepository.delete(fxCityCounty);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxCityCountyVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxCityCountyVO.class, params);
            List<FxCityCountyVO> list = result.getList();
            // 批量新增
            List<Integer> errorlist = this.saveExcel(list);
            int errorSize = errorlist.size();
            returnMsg.append("成功导入" + (result.getList().size() - errorSize) + "条，失败" + (result.getFailList().size() + errorSize) + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxCityCountyVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxCityCountyVO vo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + vo.getRowNum() + "行" + vo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            for (Integer i : errorlist) {
                returnMsg.append("第" + i + "行" + "工作区不存在,请先在工作区管理添加工作区!<br/>");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            String s = "库中该数据最多一条，请管理员清理数据库冗余数据！";
            if (s.equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    public List<Integer> saveExcel(List<FxCityCountyVO> list) {
        ArrayList<Integer> errolist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            FxCityCountyEntity entity = new FxCityCountyEntity();
            FxCityCountyVO vo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, entity);
            String errorMessage = saveOrUpdateFxCityCounty(entity);
            if (errorMessage.contains("工作区不存在")) {
                errolist.add(i + 1);
            }
        }
        return errolist;
    }

    private String saveOrUpdateFxCityCounty(FxCityCountyEntity entity) {
        String message = "OK";
        // 工作区名称
        String workspace = entity.getWorkspace();
        FxWorkareaQueryParams queryParams = new FxWorkareaQueryParams();
        queryParams.setWorkspace(workspace);
        List<FxWorkareaEntity> workareaEntities = fxWorkareaNativeRepository.listFxWorkareas(queryParams);
        if (workareaEntities == null || workareaEntities.size() <= 0) {
            message = "工作区不存在,请先添加工作区!";
        } else {
            // 市县名称
            String cityCountyName = entity.getCityCountyName();
            FxCityCountyQueryParams cityCountyQueryParams = new FxCityCountyQueryParams();
            cityCountyQueryParams.setWorkspace(workspace);
            cityCountyQueryParams.setCityCountyName(cityCountyName);
            List<FxCityCountyEntity> fxCityCountyEntities = fxCityCountyNativeRepository.listFxCityCountys(cityCountyQueryParams);
            // 若查到数据为空，则新增
            if (CollectionUtils.isEmpty(fxCityCountyEntities)) {
                this.saveFxCityCounty(entity);
            } else {
                if (workareaEntities.size() == 1) {
                    // 修改
                    FxCityCountyEntity fxCityCountyEntity = fxCityCountyEntities.get(0);
                    BeanUtil.copyPropertiesIgnoreNull(entity, fxCityCountyEntity);
                    this.updateFxCityCounty(fxCityCountyEntity);
                } else {
                    throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
                }
            }
        }
        return message;
    }

    @Override
    public String exportExcel(FxCityCountyQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxCityCountyEntity> entities = fxCityCountyNativeRepository.listFxCityCountys(queryParams);
            // 深拷贝
            ArrayList<FxCityCountyVO> vos = new ArrayList<>();
            for (FxCityCountyEntity entity : entities) {
                FxCityCountyVO vo = new FxCityCountyVO();
                BeanUtils.copyProperties(entity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "市县综合数据统计", "市县综合数据", FxCityCountyVO.class, "市县综合数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public List<FxCityCountyEntity> getFxCityCountys(FxCityCountyQueryParams queryParams) {
        List<FxCityCountyEntity> fxCityCountys = this.fxCityCountyNativeRepository.listFxCityCountys(queryParams);
        return fxCityCountys;
    }

    @Override
    public String judgeRational(FxCityCountyEntity fxCityCounty) {
        String message = "OK";
        // 工作区名称
        String workspace = fxCityCounty.getWorkspace();
        FxWorkareaQueryParams queryParams = new FxWorkareaQueryParams();
        queryParams.setWorkspace(workspace);
        List<FxWorkareaEntity> workareaEntities = fxWorkareaNativeRepository.listFxWorkareas(queryParams);
        if (workareaEntities == null || workareaEntities.size() <= 0) {
            message = "工作区不存在,请先在工作区管理添加工作区!";
        } else {
            // 市县名称
            String cityCountyName = fxCityCounty.getCityCountyName();
            FxCityCountyQueryParams cityCountyQueryParams = new FxCityCountyQueryParams();
            cityCountyQueryParams.setWorkspace(workspace);
            cityCountyQueryParams.setCityCountyName(cityCountyName);
            List<FxCityCountyEntity> fxCityCountyEntities = fxCityCountyNativeRepository.listFxCityCountys(cityCountyQueryParams);
            if (fxCityCountyEntities != null && fxCityCountyEntities.size() > 0) {
                message = "该工作区:" + workspace + "下的市县名称为" + cityCountyName + "的数据已存在！";
            }
        }
        return message;
    }

    @Override
    public List<String> getCityCountyNames() {
        List<String> cityCountyNames = fxCityCountyRepository.findCityCountyNames();
        return cityCountyNames;
    }
}
